import 'dart:async';

import 'package:amway_superapp_creator_plugin/analysis/zhuge_edit.dart';
import 'package:amway_superapp_creator_plugin/config/colors_config.dart';
import 'package:amway_superapp_creator_plugin/dialog/loading_dialog.dart';
import 'package:amway_superapp_creator_plugin/models/module_list.dart';
import 'package:amway_superapp_creator_plugin/routers/application.dart';
import 'package:amway_superapp_creator_plugin/routers/routes.dart';
import 'package:amway_superapp_creator_plugin/utils/colors_util.dart';
import 'package:amway_superapp_creator_plugin/utils/toast_util.dart';
import 'package:amway_superapp_creator_plugin/view_state.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/module_page_viewmodel.dart';
import 'package:amway_superapp_creator_plugin/views/base_view.dart';
import 'package:amway_superapp_creator_plugin/widget/flutter_reorderable_list.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:provider/provider.dart';

class MainSettingPage extends StatefulWidget {
  @override
  MainSettingPageState createState() => new MainSettingPageState();

  MainSettingPage(var ada, var amwayId, var identityMarks) {
    _ada = ada;
    _amwayId = amwayId;
    _identityMarks = identityMarks;
  }
}

var _ada;
var _amwayId;
var _identityMarks;

enum DraggingMode {
  iOS,
  Android,
}

// Returns index of item with given key
int _indexOfKey(Key key, List<ModuleItem> items) {
  return items.indexWhere((ModuleItem d) => d.key == key);
}

class Item extends StatelessWidget {
  Item({
    this.data,
    this.isFirst,
    this.isLast,
    this.draggingMode,
  });

  final ModuleItem data;
  final bool isFirst;
  final bool isLast;
  final DraggingMode draggingMode;

  Widget _buildChild(BuildContext context, ReorderableItemState state) {
    // For iOS dragging mode, there will be drag handle on the right that triggers
    // reordering; For android mode it will be just an empty container
    //
    BoxDecoration decoration;

    bool _isNotAvailable=false;

    switch (data.moduleName) {
      case "RECOMMEND":
        break;
      case "CIRCLE":
        break;
      case "NONE":
      case "PERSONAL":
      case "HEALTH_FOOD":
      case "COMBINATION":
      case "LIVE_VIDEO":
      case "ACTIVITY":
        _isNotAvailable=true;
        break;
    }

    if (state == ReorderableItemState.dragProxy ||
        state == ReorderableItemState.dragProxyFinished) {
      // slightly transparent background white dragging (just like on iOS)
      decoration = BoxDecoration(color: Color(0xD0FFFFFF));
    } else {
      bool placeholder = state == ReorderableItemState.placeholder;
      decoration = BoxDecoration(
          borderRadius: isLast?BorderRadius.only(bottomLeft: Radius.circular(ScreenUtil().setSp(15)),bottomRight: Radius.circular(ScreenUtil().setSp(15))):BorderRadius.zero,
          color: placeholder ? null : Colors.white);
    }

    
    Widget checkbox=(data.state=="ON"&&!_isNotAvailable)?CircleAvatar(
      radius: (ScreenUtil().setSp(10)),
      child: Icon(Icons.check,size: ScreenUtil().setWidth(15),),
      backgroundColor: ColorUtil.fromHex('#396E75'),
    ):Icon(Icons.radio_button_unchecked_rounded,size: ScreenUtil().setWidth(_isNotAvailable?0:23),color: Colors.grey.withOpacity(0.4),);
    String actionState = data.actionState ? "配置" : "详情";

    Widget _buildNoPass(String auditEnum) {
      if (auditEnum != null && auditEnum == "UN_PASS") {
        return Container(
          child: Image.asset(
            'picture/icon_audit_nopass.png',
            package: 'amway_superapp_creator_plugin',
          ),
          width: ScreenUtil().setWidth(75),
          margin: EdgeInsets.only(right: ScreenUtil().setWidth(12)),
        );
      } else {
        return Container();
      }
    }

    Widget dragHandle = draggingMode == DraggingMode.Android
        ? ReorderableListener(
            child: Container(
              padding: EdgeInsets.fromLTRB(
                  ScreenUtil().setWidth(16),
                  ScreenUtil().setHeight(16),
                  ScreenUtil().setWidth(0),
                  ScreenUtil().setHeight(16)),
              child: Center(
                child: Image.asset('picture/icon_move.png',
                    width: ScreenUtil().setWidth(16),
                    height: ScreenUtil().setWidth(16),
                    package: 'amway_superapp_creator_plugin'),
              ),
            ),
          )
        : Container(
      padding: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(0),
          ScreenUtil().setHeight(16),
          ScreenUtil().setWidth(0),
          ScreenUtil().setHeight(16)),
      child: Center(
        child: Container(
            width: ScreenUtil().setWidth(8),
            height: ScreenUtil().setHeight(16)),
      ),
    );




    Widget content = Container(
      decoration: BoxDecoration(
        border: Border(
            bottom: isLast || state==ReorderableItemState.placeholder
                ? BorderSide.none //
                : Divider.createBorderSide(context,width: ScreenUtil().setWidth(_isNotAvailable?0:0.5))),
      ),
      padding: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(17), 0, ScreenUtil().setWidth(17), 0),
      child: Row(
        children: [
          Container(
            child: GestureDetector(
              child: SizedBox(
                width: ScreenUtil().setWidth(30),
                height: ScreenUtil().setWidth(30),
                child: Center(
                  child: checkbox),
              ),
              onTap: () {
                if(_isNotAvailable){
                  ToastUtils.showShortToast('该模块暂未开放哦');
                  return;
                }
                _vm.onItemCheckTap(data.name);
                ZhugeEditAnalysis.editPageClickConfig("模块设置");
              },
            ),
            margin: EdgeInsets.only(right: ScreenUtil().setWidth(5)),
          ),
          Expanded(
              child: Text(data.name != null ? data.name : data.moduleName,style: TextStyle(color: ColorsConfig.c_2c2c2c.withOpacity(_isNotAvailable?0.3:1),fontWeight: FontWeight.bold,fontSize: ScreenUtil().setSp(16)),)),
          _buildNoPass(data.auditStatusEnum),
          GestureDetector(
              onTap: () {
                switch (data.moduleName) {
                  case "NONE":
                    break;
                  case "PERSONAL":
                    break;
                  case "COMBINATION":
                    break;
                  case "RECOMMEND":
                    Map<String, dynamic> parameters = {
                      'amwayAda': _ada,
                      'amwayId': _amwayId,
                    };
                    Application.router
                        .navigateTo(context, Routes.recommendProduct,
                            routeSettings: RouteSettings(arguments: parameters))
                        .then((value) => {
                              if (value != null) {_vm.updateModuleState()}
                            });
                    break;
                  case "CIRCLE":
                    Map<String, dynamic> parameters = {
                      'amwayAda': _ada,
                      'amwayId': _amwayId,
                      'identityMarks': _identityMarks,
                    };
                    print(_ada);
                    Application.router.navigateTo(context, Routes.mycircle,
                        routeSettings: RouteSettings(arguments: parameters));
                    break;
                  case "HEALTH_FOOD":
                    break;
                  case "LIVE_VIDEO":
                    break;
                  case "ACTIVITY":
                    break;
                }
                ZhugeEditAnalysis.editPageClickDetail("模块设置");
              },
              child: Text(
                actionState,
                style: TextStyle(
                    color: ColorsConfig.c_2c2c2c.withOpacity(_isNotAvailable?0.1:0.4),
                    fontSize: ScreenUtil().setSp(16)),
              )),
          dragHandle
        ],
      ),
    );

    // For android dragging mode, wrap the entire content in DelayedReorderableListener
    if (draggingMode == DraggingMode.Android) {
      content = DelayedReorderableListener(
        child: content,
      );
    }
    return Container(
        child: Opacity(
            opacity: state == ReorderableItemState.placeholder ? 0 : 1.0,
            child: content),
        decoration: decoration);
  }

  @override
  Widget build(BuildContext context) {
    return ReorderableItem(
        key: data.key, //
        childBuilder: _buildChild);
  }
}

ModulePageVM _vm;

class MainSettingPageState extends State<MainSettingPage>
    with WidgetsBindingObserver {
  DraggingMode _draggingMode = DraggingMode.iOS;

  bool _reorderCallback(Key item, Key newPosition) {
    return false;
    int draggingIndex = _indexOfKey(item, _vm.moduleItems);
    int newPositionIndex = _indexOfKey(newPosition, _vm.moduleItems);
    _vm.changeSequence(draggingIndex, newPositionIndex);
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return BaseView<ModulePageVM>(
        model: ModulePageVM(api: Provider.of(context)),
        onModelReady: (model) async {
          _vm = model;
          _vm.setData(_ada, _amwayId);
        },
        builder: (context, model, child) => WillPopScope(
              onWillPop: () async {
                if (model.isEdited) {
                  model.updateModuleList();
                  Timer(Duration(seconds: 1), () {
                    Application.router.pop(context,1);//不要给我改我回去要刷新
                  });
                } else {
                  Application.router.pop(context,1);////不要给我改我回去要刷新
                }
                ZhugeEditAnalysis.editPageClickReturn("模块设置");
                return true;
              },
              child: Scaffold(
                appBar: PreferredSize(
                  preferredSize: Size.fromHeight(ScreenUtil().setWidth(46)),
                  child: AppBar(
                    backgroundColor: Colors.white,
                    elevation: 0,
                    //去除阴影
                    brightness: Brightness.light,
                    //黑色状态栏
                    title: new Text(
                      "设置小站",
                      style: TextStyle(
                          fontSize:
                              ScreenUtil().setWidth(ScreenUtil().setSp(20)),
                          color: Colors.black,
                          fontWeight: FontWeight.bold),
                    ),
                    centerTitle: true,
                    leading: GestureDetector(
                        child: BaseView.buildBackButton(),
                        onTap: () {
                          if (model.isEdited) {
                            model.updateModuleList();
                            Timer(Duration(seconds: 1), () {
                              Application.router.pop(context,1);
                            });
                          } else {
                            Application.router.pop(context,1);
                          }
                        }),
                  ),
                ),
                body: model.state == ViewState.Busy
                    ? Center(
                        child: Container(
                            width: double.maxFinite,
                            height: double.maxFinite,
                            child: Center(
                                child: LoadingDialog(
                                    canceledOnTouchOutside: false,
                                    tipMsg: "正在保存"))))
                    : Column(
                        children: [
                          Expanded(
                            child: Container(
                              padding: EdgeInsets.fromLTRB(ScreenUtil().setWidth(16), ScreenUtil().setWidth(25), ScreenUtil().setWidth(16), 0),
                              color: Colors.white,
                              child: Column(
                                mainAxisSize: MainAxisSize.max,
                                crossAxisAlignment:
                                    CrossAxisAlignment.stretch,
                                children: [
                                  Text(
                                    '选中的板块将会在创玩空间主页显示',
                                    style: TextStyle(
                                        fontSize: ScreenUtil().setSp(12),color: ColorsConfig.c_2c2c2c.withOpacity(0.5)),
                                  ),
                                  Container(
                                    // constraints: BoxConstraints(
                                    //     maxHeight: ScreenUtil().setHeight(350)),
                                    margin: EdgeInsets.only(
                                        top: ScreenUtil().setHeight(10)),
                                    decoration: BoxDecoration(
                                        color: Colors.white,
                                        boxShadow: [
                                          BoxShadow(
                                              blurRadius:
                                                  ScreenUtil().setHeight(20),
                                              color: ColorUtil.fromHex(
                                                  '#1A000000'))
                                        ],
                                        borderRadius: BorderRadius.all(
                                            Radius.circular(
                                                ScreenUtil().setSp(15)))),
                                    child: Padding(
                                      padding: EdgeInsets.fromLTRB(
                                          0, ScreenUtil().setSp(16), 0, 0),
                                      child: ReorderableList(
                                        onReorder: _reorderCallback,
                                        child: CustomScrollView(
                                          shrinkWrap: true,
                                          slivers: <Widget>[
                                            SliverList(
                                              delegate:
                                                  SliverChildBuilderDelegate(
                                                (BuildContext context,
                                                    int index) {
                                                  return Item(
                                                    data: model.moduleItems
                                                        .elementAt(index),
                                                    // first and last attributes affect border drawn during dragging
                                                    isFirst: index == 0,
                                                    isLast: index ==
                                                        model.moduleItems
                                                                .length -
                                                            1,
                                                    draggingMode:
                                                        _draggingMode,
                                                  );
                                                },
                                                childCount:
                                                    model.moduleItems.length,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                          // Container(
                          //   width: double.infinity,
                          //   height: ScreenUtil().setHeight(100),
                          //   decoration: BoxDecoration(
                          //     color: Colors.white,
                          //     boxShadow: [
                          //       BoxShadow(
                          //           color: ColorUtil.fromHex('#26000000'),
                          //           offset:
                          //               Offset(0, -ScreenUtil().setHeight(2)),
                          //           blurRadius: ScreenUtil().setHeight(15))
                          //     ],
                          //   ),
                          //   child: Padding(
                          //     padding: EdgeInsets.fromLTRB(
                          //         ScreenUtil().setWidth(16),
                          //         ScreenUtil().setHeight(16),
                          //         ScreenUtil().setWidth(16),
                          //         ScreenUtil().setHeight(38)),
                          //     child: FlatButton(
                          //       onPressed: () {
                          //         model.updateModuleList();
                          //       },
                          //       color: ColorUtil.fromHex('#FF396E75'),
                          //       child: Center(
                          //         child: Text('完成',
                          //             style: TextStyle(color: Colors.white)),
                          //       ),
                          //       shape: StadiumBorder(),
                          //     ),
                          //   ),
                          // )
                        ],
                      ),
              ),
            ));
  }

  @override
  void initState() {
    ZhugeEditAnalysis.editPage(EditPageType.mainPage);
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  void didUpdateWidget(MainSettingPage oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
  }
}
